/*
 * FileName：MassSendCtrl.java 
 * <p>
 * Copyright (c) 2017-2020 <a href="https://www.smartwx.info">hermit(1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.smart.wx.wxcms.ctrl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.smart.common.BaseCtrl;
import com.smart.common.exception.WxError;
import com.smart.common.exception.WxErrorException;
import com.smart.common.util.AjaxResult;
import com.smart.common.util.SessionUtil;
import com.smart.common.util.WxMemoryCacheClient;
import com.smart.wx.wxapi.process.MpAccount;
import com.smart.wx.wxapi.process.MsgType;
import com.smart.wx.wxapi.process.WxApiClient;
import com.smart.wx.wxcms.entity.AccountFans;
import com.smart.wx.wxcms.entity.MediaFiles;
import com.smart.wx.wxcms.entity.MsgRecord;
import com.smart.wx.wxcms.entity.UserTag;
import com.smart.wx.wxcms.service.AccountFansService;
import com.smart.wx.wxcms.service.ImgResourceService;
import com.smart.wx.wxcms.service.MediaFileService;
import com.smart.wx.wxcms.service.MsgNewsService;
import com.smart.wx.wxcms.service.MsgRecordService;
import com.smart.wx.wxcms.service.UserTagService;

/**
 * 群发消息控制器
 * 
 * @author nigulading
 *
 */
@Controller
@RequestMapping("/massSend")
public class MassSendCtrl  extends BaseCtrl {

	private Logger log=LoggerFactory.getLogger(MassSendCtrl.class);
	@Autowired
	private UserTagService userTagService;
	@Autowired
	private AccountFansService accountFansService;
	@Autowired
	private ImgResourceService imgResourceService;
	@Autowired
	private MediaFileService mediaFileService;
    @Autowired
    private MsgNewsService msgNewsService;
    @Autowired
    private MsgRecordService msgRecordService;
	
	/**
	 * 群发消息
	 * @param type
	 * @param sourceId
	 * @param tarGet
	 * @param sex
	 * @param tag
	 * @return
	 * @throws WxErrorException
	 */
	@RequestMapping(value = "/sendToMass")
	@ResponseBody
	public AjaxResult sendToMass(String type,//消息类型
								String sourceId,//资源id-数据库中的素材数据主键或文本内容
								String tarGet,//tag类型 全部用户还是按标签选择
								String sex,//性别选择 0全部、1男、2女。
								String tag//标签id 特指微信的标签id
								) throws WxErrorException{
		log.info("开始群发");
		log.info("sendToMass:{},{},{},{},{}", type, sourceId, tarGet,sex,tag);
		MpAccount mpAccount = WxMemoryCacheClient.getMpAccount();
		/**
		 * 优先判断当月是否已经达到4条群发消息的上限
		 */
		List<MsgRecord> msgCount = msgRecordService.queryByMonth(mpAccount.getAccount());
		//每月四条是否超限的标识。超限为true
		Boolean check= false;
		if(msgCount!=null && !msgCount.isEmpty() && msgCount.size()>=4) {
			
//			return AjaxResult.failure("当月发送的消息已经达到上限，不能再发送！！！");
			//这里逻辑做出修改，超过四条直接使用客服接口
			/**
			 * 先查询标签下粉丝数(或全部粉丝数)，然后遍历粉丝进行客服接口调用。
			 */
			check=true;
		}
		/**
		 * 逻辑处理：
		 * 先判断tarGet是否是all,如果是，再去判断性别sex，如果性别是0，则选择的是全部用户，直接使用标签群发接口，全部群发；
		 * 如果性别不是0，就要通过性别查询该性别的用户，通过openid接口群发消息，OpenID最少2个，最多10000个；
		 * 如果tarGet是否是tag，直接使用标签群发消息，其他不用判断。
		 */
		String mediaId="";
		MsgType mty= null;
		//添加群发记录
		MsgRecord msgRecord =new MsgRecord();
		msgRecord.setAccount(mpAccount.getAccount());
		msgRecord.setCreateTime(new Date());
		msgRecord.setMsgType(type);
		msgRecord.setUserId(SessionUtil.getUserId());
		msgRecord.setDelStatus(0);//默认都是未删除-只有图文和视频支持api删除
		//图文
		if(type.equals("mpnews")){
			mty=MsgType.MPNEWS;
			mediaId=msgNewsService.getById(sourceId).getMediaId();
			msgRecord.setMediaId(mediaId);
		}else if(type.equals("image")){
			mty=MsgType.Image;
			mediaId=imgResourceService.getImg(sourceId).getMediaId();
			msgRecord.setMediaId(mediaId);
		}else if(type.equals("voice")||type.equals("mpvideo")){
			mty=type.equals("voice")?MsgType.Voice:MsgType.MPVIDEO;
			MediaFiles media=new MediaFiles();
			media.setId(Long.parseLong(sourceId));
			media.setAccount(mpAccount.getAccount());
			mediaId=mediaFileService.getFileBySou(media).getMediaId();
			msgRecord.setMediaId(mediaId);
		}else if(type.equals("text")){
			mty=MsgType.Text;
			mediaId=sourceId;//为文本内容
			msgRecord.setContent(sourceId);
		}

		//tarGet=all sex=0 
		if(tarGet.equals("all") && sex.equals("0")){
			//4条群发超限后走客服接口
			if(check){
				List<AccountFans> listUsers = accountFansService.list(new AccountFans());
				for (int i = 0; i < listUsers.size(); i++) {
					//防止出错直接try
					try {
						JSONObject reCustomMsg = WxApiClient.sendCustomMsg(mpAccount, listUsers.get(i).getOpenId(), type, mediaId);
						log.info("记录到日志=> reCustomMsg: {}",reCustomMsg.toJSONString());
					} catch (Exception e) {
						log.error("ctrl=> sendCustomMsg"+e.getMessage(), e);
					}
				}
				return AjaxResult.saveSuccess();
			}
			
			JSONObject res = WxApiClient.massSendByTag(mpAccount, true, 0, type, mediaId);
			
			log.info("群发成功：{}",res.toJSONString());
			if(type.equals("mpnews")){
				msgRecord.setMsgDataId(String.valueOf(res.getLongValue("msg_data_id")));
			}
			msgRecord.setMsgId(String.valueOf(res.getLongValue("msg_id")));
			msgRecord.setMsgStatus(res.getString("errmsg").indexOf("success")!=-1?1:0);
			try {
				msgRecordService.insert(msgRecord);
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage(), e);
			}
			return AjaxResult.saveSuccess();
			
		}else if(tarGet.equals("all")&&!sex.equals("0")){
			AccountFans acf=new AccountFans();
			acf.setAccount(mpAccount.getAccount());
			if(sex.equals("1")){//男
				acf.setGender(1);
			}else{
				acf.setGender(0);//女
			}
			List<AccountFans> fans = accountFansService.getAllBySex(acf);
			
			if(fans==null||fans.isEmpty()||fans.size()<2||fans.size()>10000){
				throw new WxErrorException(WxError.newBuilder().setErrorCode(40031).setErrorMsg("不合法的 openid 列表").build());
			}
			
			List<String> openids = new ArrayList<String>();
			for (int i = 0; i < fans.size(); i++) {
				openids.add(fans.get(i).getOpenId());
			}
			//4条群发超限后走客服接口
			if(check){
				for (int i = 0; i < openids.size(); i++) {
					//防止出错直接try
					try {
						JSONObject reCustomMsg = WxApiClient.sendCustomMsg(mpAccount, openids.get(i), type, mediaId);
						log.info("记录到日志=> reCustomMsg: {}",reCustomMsg.toJSONString());
					} catch (Exception e) {
						log.error("ctrl=> sendCustomMsg"+e.getMessage(), e);
					}
				}
				return AjaxResult.saveSuccess();
			}
			if(type.equals("text")){
				JSONObject res = WxApiClient.massSendTextByOpenIds(openids, mediaId, mpAccount);
				log.info("群发成功：{}",res.toJSONString());
				if(type.equals("mpnews")){
					msgRecord.setMsgDataId(String.valueOf(res.getLongValue("msg_data_id")));
				}
				msgRecord.setMsgId(String.valueOf(res.getLongValue("msg_id")));
				msgRecord.setMsgStatus(res.getString("errmsg").indexOf("success")!=-1?1:0);
				try {
					msgRecordService.insert(msgRecord);
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e.getMessage(), e);
				}
				return AjaxResult.saveSuccess();
			}else{
				JSONObject res = WxApiClient.massSendByOpenIds(openids, mediaId, mty, mpAccount);
				log.info("群发成功：{}",res.toJSONString());
				if(type.equals("mpnews")){
					msgRecord.setMsgDataId(String.valueOf(res.getLongValue("msg_data_id")));
				}
				msgRecord.setMsgId(String.valueOf(res.getLongValue("msg_id")));
				msgRecord.setMsgStatus(res.getString("errmsg").indexOf("success")!=-1?1:0);
				try {
					msgRecordService.insert(msgRecord);
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e.getMessage(), e);
				}
				return AjaxResult.saveSuccess();
			}
		}else{
			//4条群发超限后走客服接口
			if(check){
				List<String> openIds =UserTagCtrl.forFansByTag(new ArrayList<String>(), Integer.parseInt(tag), "");
				for (int i = 0; i < openIds.size(); i++) {
					//防止出错直接try
					try {
						JSONObject reCustomMsg = WxApiClient.sendCustomMsg(mpAccount, openIds.get(i), type, mediaId);
						log.info("记录到日志=> reCustomMsg: {}",reCustomMsg.toJSONString());
					} catch (Exception e) {
						log.error("ctrl=> sendCustomMsg"+e.getMessage(), e);
					}
				}
				return AjaxResult.saveSuccess();
			}
			
			JSONObject res = WxApiClient.massSendByTag(mpAccount, false, Integer.parseInt(tag), type, mediaId);
			log.info("群发成功：{}",res.toJSONString());
			if(type.equals("mpnews")){
				msgRecord.setMsgDataId(String.valueOf(res.getLongValue("msg_data_id")));
			}
			msgRecord.setMsgId(String.valueOf(res.getLongValue("msg_id")));
			msgRecord.setMsgStatus(res.getString("errmsg").indexOf("success")!=-1?1:0);
			try {
				msgRecordService.insert(msgRecord);
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage(), e);
			}
			return AjaxResult.saveSuccess();
		}
		
	}
	/**
	 * 获取当前公众号所有的公众号
	 * @return
	 */
	@RequestMapping(value = "/tagAll")
	@ResponseBody
	public AjaxResult tagAll(){
		log.info("获取群发使用的所有标签");
		UserTag searchEntity =new UserTag();
		searchEntity.setPageSize(300);//微信端标签总共300个标签，这里直接获取所有
		MpAccount mpAccount = WxMemoryCacheClient.getMpAccount();
		searchEntity.setAccount(mpAccount.getAccount());
		List<UserTag> list = userTagService.listForPage(searchEntity);
		if (CollectionUtils.isEmpty(list)) {
			return AjaxResult.success();
		}
		return getResult(searchEntity,list);
		
	}
}
